package cn.clx.basic.service.impl;

import cn.clx.basic.constants.BaseConstant;
import cn.clx.basic.dto.LoginDto;
import cn.clx.basic.dto.RegisterDto;
import cn.clx.basic.dto.WeChatDto;
import cn.clx.basic.exception.BusinessException;
import cn.clx.basic.service.ILoginService;
import cn.clx.basic.util.AjaxResult;
import cn.clx.basic.util.HttpClientUtils;
import cn.clx.basic.util.MD5Utils;
import cn.clx.basic.util.StrUtils;
import cn.clx.user.domain.Logininfo;
import cn.clx.user.domain.User;
import cn.clx.user.domain.Wxuser;
import cn.clx.user.mapper.LogininfoMapper;
import cn.clx.user.mapper.UserMapper;
import cn.clx.user.mapper.WxuserMapper;
import cn.clx.user.service.ILogininfoService;
import com.alibaba.fastjson.JSONObject;
import jdk.nashorn.internal.parser.Token;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 账号密码登录
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> account(LoginDto dto) {
        String password = dto.getPassword();
        String username = dto.getUsername();
        Integer type = dto.getType();
        //校验
        if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)||type==null){
            throw new BusinessException("参数不能为空");
        }
        Logininfo logininfo =logininfoMapper.loadByUsernameAndtype(dto);
        if(logininfo==null){
            throw new BusinessException("用户不存在,请注册");
        }
        String salt = logininfo.getSalt();
        String Md5password = MD5Utils.encrypByMd5(password + salt);
        if(!Md5password.equals(logininfo.getPassword())){
            throw new BusinessException("密码错误");
        }
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30,TimeUnit.MINUTES);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);
        return map;

    }

    /**
     * 微信登录
     * @param dto
     * @return
     */
    @Override
    public AjaxResult wechat(WeChatDto dto) {
        String code = dto.getCode();
        if(code==null){
            throw new BusinessException("我的code呢，我参数呢");
        }
        String tokenUrl = BaseConstant.WeChatConstants.TOKEN_URL;
        String url = tokenUrl.replace("CODE", code)
                .replace("APPID",BaseConstant.WeChatConstants.APPID)
                .replace("SECRET",BaseConstant.WeChatConstants.SECRET);
       // String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxd853562a0548a7d0&secret=4a5d5615f93f24bdba2ba8534642dbb6&code="+code+"&grant_type=authorization_code";
        //通过code 拿到token和openid
        String httpGet = HttpClientUtils.httpGet(url);
        JSONObject jsonObject = JSONObject.parseObject(httpGet);
        String accesstoken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        //通过openid查询wxuser是否有此微信号信息
        Wxuser wxuser= wxuserMapper.loadbyOpenId(openid);
        if(wxuser!=null){
            User user = userMapper.loadById(wxuser.getUserId());
            Logininfo logininfo =logininfoMapper.loadById(user.getLogininfoId());
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(token,logininfo,30,TimeUnit.MINUTES);
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",token);
            map.put("logininfo",logininfo);
            return AjaxResult.getAjaxResult().setResultObj(map);
        }
        //wxuser表中没有此微信信息
        String binderUrl ="?access_token="+accesstoken+"&openid="+openid;

        return AjaxResult.getAjaxResult().setSuccess(false).setResultObj(binderUrl);
    }

    /**
     * 微信绑定
     * @param dto
     * @return
     */
    @Override
    public AjaxResult binder(WeChatDto dto) {
        String accessToken = dto.getAccessToken();
        String openId = dto.getOpenId();
        String phone = dto.getPhone();
        String password = dto.getPassword();
        String verifyCode = dto.getVerifyCode();
        if(StringUtils.isEmpty(accessToken)||
                StringUtils.isEmpty(openId)||
                StringUtils.isEmpty(phone)||
                StringUtils.isEmpty(password)||
                StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("参数不能为空！！！");
        }

        Object code = redisTemplate.opsForValue().get(BaseConstant.RegisterConstants.WECHAT_SMS_PREFIX + phone);
        String oldcode = code.toString().split(":")[0];
        if(!verifyCode.equalsIgnoreCase(oldcode)){
            throw new BusinessException("验证码不正确，请重试");
        }

        //通过输入的电话查询一下以前是否登录过
        User user = userMapper.loadByPhone(phone);
        Logininfo logininfo=null;
        if(user!=null){ //存在user进行绑定
            logininfo = logininfoMapper.loadById(user.getLogininfoId());
        }else{
            //user不存在
            //新建一个user
            user =dto2user(dto);
            logininfo = new Logininfo();
            BeanUtils.copyProperties(user,logininfo);
            logininfo.setType(1);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }
        //根据token和openid来获取微信用户信息
        String WXUSER_URL=BaseConstant.WeChatConstants.WXUSER_URL;
        String wechaturl = WXUSER_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        //String httpGet = HttpClientUtils.httpGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId);
        String httpGet = HttpClientUtils.httpGet(wechaturl);
        //把微信信息json格式 转换成一个domain对象
        Wxuser wxuser = JSONObject.parseObject(httpGet, Wxuser.class);
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);

        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30,TimeUnit.MINUTES);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);
        return AjaxResult.getAjaxResult().setResultObj(map);
    }

    private User dto2user(WeChatDto dto) {
        User user = new User();
        String phone = dto.getPhone();
        String password = dto.getPassword();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(16);
        user.setSalt(salt);
        user.setPassword(MD5Utils.encrypByMd5(password+salt));
        return user;
    }
}
